<?php

namespace app\service;

use app\model\ClueMobile;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderOtherCertificateBusiness;
use app\model\OrderPersonCertificateRegister;
use app\model\OrderTransactionRecord;
use app\model\SystemCertificate;
use app\stateData;
use DateTime;
use think\facade\Cache;
use think\facade\Db;

class Certificate
{

    //过期时间 单位”天“
    protected $gqDate = 1;

    protected $zssh = "ZS"; //证书审核
    protected $zsbl = "ZSBL";//证书办理
    protected $qyzs = "QYZS";//企业证书
    protected $dz = "QYDZ";//倒证
    protected $zszc = "QYZSZC";//公司证书
    protected $PaymentCode = "FKJL";//付款单
    protected $CollectionCode = "SKJL";//收款单

    /**
     * 证书编号生成
     */
    public function CertificateCodeCreate($module = 'ZS'): string
    {
        //如果收付款 则切换code
        if ($module == $this->PaymentCode || $module == $this->CollectionCode){
            return $this->getCacheCode ($module.date('ymd'),$module,'finance_code');
        }

        return $this->getCacheCode ($module.date('ymd'),$module,'code');

    }


    public function getCacheCode($ymd,$module,$reKey)
    {
        // 连接redis
        $redis = Cache::store('redis');
        //获取过期时间戳
        $cdate = strtotime(date("Y-m-d",strtotime("+".$this->gqDate." day")));
        //过期剩余时间
        $expire = $cdate-time ();

        $codeNum = 1;

        if (!$redis->has($reKey)){
            //查询当日订单个数
            $toDayNum = $this->getToDayOrderNum($module);
            if ($toDayNum > 0){
                $redis->set ($reKey,$toDayNum, $expire);
                return $ymd.$this->completionCodeNum($toDayNum);
            }

            $redis->set ($reKey,$codeNum, $expire);
            return $ymd.$this->completionCodeNum($codeNum);
        }

        return $ymd.$this->completionCodeNum($redis->inc($reKey));

    }

    /**
     * 查询今日订单个数
     */
    public function getToDayOrderNum($module)
    {
        $orderPersonCertificateRegModel = new OrderPersonCertificateRegister();//证书审核
        $orderEnterPriseExchangeModel = new OrderEnterpriseExchange();//倒证
        $orderEnterPriseCompanyModel = new OrderEnterpriseCompany(); //公司证书
        $orderEnterpriseCertificateRegisterModel = new OrderEnterpriseCertificateRegister(); //公司需求
        $orderEnterpriseCertificateBusinessModel = new OrderEnterpriseCertificateBusiness();//企业证书
        $orderOtherCertificateBusiness = new OrderOtherCertificateBusiness();//证书办理
        $OrderTransactionRecordModel = new OrderTransactionRecord();
        $toDayNum = 0;
        //查询当日是否有存在该系列证书数据
        if ($module == $this->zssh){
            $toDayNum += $orderPersonCertificateRegModel->getToDayCountFindModel();
        }else if ($module == $this->zszc){
            $toDayNum += $orderEnterPriseCompanyModel->getToDayCountFindModel();
            $toDayNum += $orderEnterpriseCertificateRegisterModel->getToDayCountFindModel();
        }else if ($module == $this->dz){
            $toDayNum += $orderEnterPriseExchangeModel->getToDayCountFindModel();
        }else if ($module == $this->zsbl){
            $toDayNum += $orderOtherCertificateBusiness->getToDayCountFindModel();
        }else if ($module == $this->qyzs){
            $toDayNum += $orderEnterpriseCertificateBusinessModel->getToDayCountFindModel();
        }else if($module == $this->PaymentCode){ //付款
            $toDayNum += $OrderTransactionRecordModel->getToDayCountFindModel(2);
        }else if($module == $this->CollectionCode){//收款
            $toDayNum += $OrderTransactionRecordModel->getToDayCountFindModel(1);
        }

        return $toDayNum;
    }


    /**
     *字符串补全4位
     */
    public function completionCodeNum($codeNum,$le=4)
    {
        if (mb_strlen ($codeNum) < $le){
            $codeNum = str_pad($codeNum,$le,'0',STR_PAD_LEFT );
        }

        return $codeNum;
    }


    /**
     * 通过证书专业id获取详细证书详情
     */
    public function setCertificateDetails($data)
    {
        $zszy = '';
        $zsdj = '';
        $zslb = '';
        $zslx = '';
        //拼接呈现数据
        foreach ($data as $i => $iValue) {
            if (isset($iValue['certificate_id'])){
                if ($iValue['certificate_id'] > 0 && isset($iValue['certificate_id'])){
                    $zszy = Db::table('system_certificate')->where(['id'=> $iValue['certificate_id']])->find();
                    $zszy_parent_id = $zszy ? $zszy['parent_id']: 0;
                    $zsdj = Db::table('system_certificate')->where(['id'=>$zszy_parent_id])->find();
                    $zsdj_parent_id = $zsdj ? $zsdj['parent_id']: 0;
                    $zslb = Db::table('system_certificate')->where(['id'=>$zsdj_parent_id])->find();
                    $zslb_parent_id = $zslb ? $zslb['parent_id']: 0;
                    $zslx = Db::table('system_certificate')->where(['id'=>$zslb_parent_id])->find();
                    $data[$i]['certificate_leixing'] = $zslx ? $zslx['certificate_name']: '';
                    $data[$i]['certificate_leibie'] = $zslb ? $zslb['certificate_name']: '';
                    $data[$i]['certificate_dengji'] =$zsdj ? $zsdj['certificate_name'] : '';
                    $data[$i]['certificate_zhuanye'] =$zszy? $zszy['certificate_name'] : '';
                }else{
                    $data[$i]['certificate_leixing'] = '';
                    $data[$i]['certificate_leibie'] = '';
                    $data[$i]['certificate_dengji'] = '';
                    $data[$i]['certificate_zhuanye'] = '';
                }
            }
        }
        return $data;
    }


    /**
     * 递归寻找相关子类id
     * @return string
     */
    public function getCertificateChildsIdStr($id,$data,$bool=true): string
    {
        $str = '';
        if ($bool){
            $str = $id.',';
        }

        foreach ($data as $datum) {

            if ($datum['parent_id'] == $id){

                if (!empty($this->getCertificateChildsIdStr ($datum['id'],$data))){
                    $str .= $this->getCertificateChildsIdStr ($datum['id'],$data);
                }
            }
        }
        return $str;
    }

    /**
     * 递归寻找最后一级
     * @param $id
     * @param $data
     * @return string
     */
    public function getCertificateFinalId($id,$data,$bool=true)
    {
        $str = '';
        if ($bool){
            $str = $id;
        }
        foreach ($data as $datum) {

            if ($datum['parent_id'] == $id){

                if (!empty($this->getCertificateFinalId ($datum['id'],$data))){
                    $str = $this->getCertificateFinalId ($datum['id'],$data);
                }
            }
        }
        return $str;
    }

    /**
     * 获取关联表手机号码
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function arrMobile($data)
    {
        $mobileModel = new ClueMobile();
        foreach ($data as $i => $iValue) {
            $enMob = $mobileModel->getPersonIdMobileModel($iValue['id'],2);
            if (!empty($enMob)){
                $data[$i]['mobiles'] = $enMob[0]['mobile'];
                $data[$i]['name'] = $enMob[0]['name'];
            }else{
                $data[$i]['mobiles'] = '';
                $data[$i]['name'] = '';
            }
        }
        return $data;
    }

    /**
     * 添加redis缓存 新加的单条数据手机号码处理
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function arrFindMobile($data)
    {
        if (empty($data)){
            return [];
        }
        $mobileModel = new ClueMobile();
        $enMob = $mobileModel->getPersonIdMobileModel($data['id'],2);

        if (!empty($enMob)){
            $data['mobiles'] = $enMob[0]['mobile'];
            $data['name'] = $enMob[0]['name'];
        }else{
            $data['mobiles'] = '';
            $data['name'] = '';
        }


        return $data;
    }


    /**
     * 补全订单详情内容
     */
    public function DzDetailsSup($data)
    {
        $datas = [
            'create_date',
            'certificate_code',
            'business_id',
            'order_status',
            'employ_unit_title',
            'employ_unit_name',
            'employ_unit_mobile',
            'unit_reg_title',
            'out_org',
            'out_uid',
            'out_price',
            'out_unit',
            'out_name',
            'out_mobile',
            'certificate_leixing',
            'certificate_leibie',
            'certificate_dengji',
            'certificate_zhuanye',
            'certificate_b',
            'social_security',
            'cycle',
            'project',
            'transfer',
            'get_org',
            'get_uid',
            'get_price',
            'person_name',
            'id_card',
            'reg_file',
            'performance',
            'electronic_certificate_file_illustrate',
            'electronic_certificate_date',
            'b_electronic_certificate_file',
            'b_electronic_certificate_date',
            'b_reg_electronic_certificate_date'
        ];

        foreach ($datas as $iValue) {

            if (!array_key_exists ($iValue,$data)){
                $data[$iValue] = '';
            }
        }
        return $data;
    }

    //拆分证书信息
    public function splitCer($post)
    {
        if(!isset($post['certificate_id'])){
            return $post;
        }
        if (is_array ($post['certificate_id'])){
            $datas = $post['certificate_id'];
        }else{
            $datas = explode (',',$post['certificate_id']);
        }
        $count = count($datas);

        if ($count == 1){
            $post['certificate_leixing'] = $datas[0];
            $post['certificate_leibie'] = 0;
            $post['certificate_dengji'] = 0;
            $post['certificate_zhuanye'] = 0;
        }

        if ($count == 2){
            $post['certificate_leixing'] = $datas[0];
            $post['certificate_leibie'] = $datas[1];
            $post['certificate_dengji'] = 0;
            $post['certificate_zhuanye'] = 0;
        }

        if ($count == 3){
            $post['certificate_leixing'] = $datas[0];
            $post['certificate_leibie'] = $datas[1];
            $post['certificate_dengji'] = $datas[2];
            $post['certificate_zhuanye'] = 0;
        }

        if ($count == 4){
            $post['certificate_leixing'] = $datas[0];
            $post['certificate_leibie'] = $datas[1];
            $post['certificate_dengji'] = $datas[2];
            $post['certificate_zhuanye'] = $datas[3];
        }
        //转字符串进库
        $post['certificate_id'] = implode (',',$datas);
        return $post;
    }

    /**
     * 通过certificate_id 获取4级详情
     * @param $post
     * @return mixed
     */
    public function getCertificateInfo($post)
    {
        $certificateModel = new SystemCertificate();
        if(!isset($post['certificate_id'])){
            return $post;
        }
        if (is_array ($post['certificate_id'])){
            $datas = $post['certificate_id'];
        }else{
            $datas = explode (',',$post['certificate_id']);
        }
        $count = count($datas);

        $certificate_text = '';
        if ($count == 1){
            $post['certificate_leixing'] = $certificateModel->getWhereIdCertificateModel ($datas[0]);
            $certificate_text .= $post['certificate_leixing'];
        }

        if ($count == 2){
            $post['certificate_leixing'] = $certificateModel->getWhereIdCertificateModel ($datas[0]);
            $post['certificate_leibie'] = $certificateModel->getWhereIdCertificateModel ($datas[1]);
            $certificate_text .= $post['certificate_leixing'].'/'.$post['certificate_leibie'];
        }

        if ($count == 3){
            $post['certificate_leixing'] = $certificateModel->getWhereIdCertificateModel ($datas[0]);
            $post['certificate_leibie'] = $certificateModel->getWhereIdCertificateModel ($datas[1]);
            $post['certificate_dengji'] = $certificateModel->getWhereIdCertificateModel ($datas[2]);
            $certificate_text .= $post['certificate_leixing'].'/'.$post['certificate_leibie'].'/'.$post['certificate_dengji'];
        }

        if ($count == 4){
            $post['certificate_leixing'] = $certificateModel->getWhereIdCertificateModel ($datas[0]);
            $post['certificate_leibie'] = $certificateModel->getWhereIdCertificateModel ($datas[1]);
            $post['certificate_dengji'] = $certificateModel->getWhereIdCertificateModel ($datas[2]);
            $post['certificate_zhuanye'] = $certificateModel->getWhereIdCertificateModel ($datas[3]);
            $certificate_text .= $post['certificate_leixing'].'/'.$post['certificate_leibie'].'/'.$post['certificate_dengji'].'/'.$post['certificate_zhuanye'];
        }

        $post['certificate_text'] = $certificate_text;
        return $post;
    }



    /**
     * 获取证书id下面所有专业
     * @param $id
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setCertificateZhuanye($id,$where)
    {
        $certificate = new SystemCertificate();
        $financeSer = new FinanceServer();

        //获取该证书信息
        $cerData = $certificate->getIdLikeFindModel($id);

        $result = [];
        if ($cerData){
//            if ($cerData['parent_id'] == 0){
                $cerDa = $certificate->getIdSubClass($cerData['id']);
                if (!empty($cerDa)){
                    foreach ($cerDa as $item) {
                        $cerDas = $certificate->getIdSubClass($item['id']);
                        if (!empty($cerDas)){
                            foreach ($cerDas as $items) {
                                $cerDass = $certificate->getIdSubClass($items['id']);
                                if (!empty($cerDass)){

                                    foreach ($cerDass as &$cerDassItem) {
                                        $cerDassItem['certificate_name'] = $cerData['certificate_name'].'/'.$item['certificate_name'].'/'.$items['certificate_name'].'/'.$cerDassItem['certificate_name'];
                                        $result[] = $cerDassItem;
                                    }

                                }else{
//                                    foreach ($cerDas as $three) {
                                        $items['certificate_name'] = $cerData['certificate_name'].'/'.$item['certificate_name'].'/'.$items['certificate_name'];
                                        $result[] = $items;
//                                    }
                                }
                            }
                        }else{
//                            foreach ($cerDa as $itemss) {
                                if ($item['certificate_type'] <= 3){
                                    continue;
                                }
                                $item['certificate_name'] = $cerData['certificate_name'].'/'.$item['certificate_name'];
                                $result[] = $item;
//                            }
                        }
                    }
                }
//            }
//        }
        }

        if (!empty($where)){
           $result = $financeSer->search_users ($result,'certificate_name','like',$where);
        }
        return $result;
    }


    /**
     * 通过证书id 寻找父集名称
     */
    public function getParentName($id)
    {
        $certificate = new SystemCertificate();
        if (!$id) return '';
        //查询该证书名称
        $name = '';
        $reData = $certificate->getParentIdName ($id);
        if(empty($reData['parent_id'])){
            $name = $reData['certificate_name'];
        }else{
            $reDatas = $certificate->getParentIdName ($reData['parent_id']);
            if (empty($reDatas['parent_id'])){
                if (empty($reDatas['certificate_name'])){
                    return "";
                }
                $name = $reDatas['certificate_name'].'/'.$reData['certificate_name'];
            }else{
                $reDatass = $certificate->getParentIdName ($reDatas['parent_id']);
                if (empty($reDatass['parent_id'])){
                    if (empty($reDatass['certificate_name'])){
                        return "";
                    }
                    $name = $reDatass['certificate_name'].'/'.$reDatas['certificate_name'].'/'.$reData['certificate_name'];
                }else{
                    $reDatasss = $certificate->getParentIdName ($reDatass['parent_id']);
                    if (empty($reDatasss['parent_id'])){
                        if (empty($reDatasss['certificate_name'])){
                            return "";
                        }
                        $name = $reDatasss['certificate_name'].'/'.$reDatass['certificate_name'].'/'.$reDatas['certificate_name'].'/'.$reData['certificate_name'];
                    }
                }
            }
        }

        return $name;
    }
}